package com.rcp.login;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/ChangePassword")
public class ChangePassword extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private String tmpPass = "";
	private String tmpUsername = "";

	public void init() throws ServletException {

	}


	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		String username  = request.getParameter("username");
		String oldPassword  = request.getParameter("oldPassword");
		String newPassword  = request.getParameter("newPassword");
		String newPassword2 = request.getParameter("newPassword2");
		
		String home = request.getParameter("home");

		boolean isUsernameError = false;
		boolean isOldPasswordEmpty = false;
		boolean isNewPasswordError = false;
		boolean isValid = false;

		if(oldPassword != null || newPassword != null || newPassword2 != null || username != null)
		{

			if(username == null)
				isUsernameError = true;
			else
				isUsernameError = onlyAlphabetChecker(username);

			if(oldPassword == null)
				isOldPasswordEmpty = true;

			if(newPassword == null || newPassword2 == null)
				isNewPasswordError = true;
			else
				isNewPasswordError = identicalChecker(newPassword, newPassword2);

			if(!isOldPasswordEmpty && !isNewPasswordError)
				isValid = true;
		}

		// Define connection variables
		String className = "com.mysql.jdbc.Driver";
		//String url		 = "jdbc:mysql://cs3.calstatela.edu:8080/cs437group01";
		String url		 = "jdbc:mysql://cs3.calstatela.edu:3306/cs437group01";
		String dbusername  = "cs437group01";
		String dbpassword  = "VHj#dj!v";

		try{
			// Include the driver class
			Class.forName( className );

			// Establish a connection to the database
			Connection connection =
					DriverManager.getConnection(url, dbusername, dbpassword);

			String retrieveOldPasswordQuery = "SELECT * FROM Employees WHERE username = '" + username + "'  AND  password = '"+oldPassword+"'";

			// Get a reference to the statement object that will execute our query
			// on the server
			Statement statement = connection.createStatement();

			// Execute the query and Store the returned records (ResultSet)
			ResultSet resultSet = statement.executeQuery(retrieveOldPasswordQuery);

			while ( resultSet.next() ) 
			{
				tmpUsername = resultSet.getString("username");
				tmpPass = resultSet.getString("password");
			}
			connection.close();

		}
		catch(SQLException e){		
			e.printStackTrace();
		}
		catch(ClassNotFoundException e){
			e.printStackTrace();
		}

		if (username == null) username = "";
		if (oldPassword == null) oldPassword = "";
		if (newPassword == null) newPassword = "";
		if (newPassword2 == null) newPassword2 = "";


		if(!username.equals(tmpUsername)) isUsernameError = true;
		if(!oldPassword.equals(tmpPass)) isOldPasswordEmpty = true;

		response.setContentType("text/html");

		PrintWriter out = response.getWriter();

		if(!isValid)
		{
			out.println("<html xmlns='http://www.w3.org/1999/xhtml'>");
			out.println("<head>");
			out.println("<meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />");
			out.println("<title>Change Password</title>");
			out.println("<link rel='stylesheet' type='text/css' href='css/style.css' />");
			out.println("<script type='text/javascript' src='js/rightclick.js'></script>");
			out.println("</head>");
			out.println("<body><div id='header'><h1>Change Password</h1></div>");
			
			out.println("<a href='/rcp-svn/" + home + "'> HOME </a>");
			
			out.println("<div id='wrapper'>");
			out.println("<div id='steps'>");
			out.println("<form action='ChangePassword' method='post'>");
			out.println("<fieldset class='step'>");
			out.println("<legend>Password Information</legend>");

			out.println("<p>");
			out.println("<label for='username'> Username:</label>");
			out.println("<input type='text' value='" + username + "' name='username' id='username' />");

			if (isUsernameError)
				out.println("<span class='error'>Username cannot be found</span>");
			out.println("<p>");
			out.println("<label for='OldPassword'>Old Password:</label>");
			out.println("<input type='password' value='" + oldPassword + "' name='oldPassword' id='oldPassword' />");

			if (isOldPasswordEmpty)
				out.println("<span class='error'>Invalid Password.</span>");

			out.println("</p>");
			out.println("<p>");
			out.println("<label for='newPassword'>Enter Your New Password:</label>");
			out.println("<input type='password' value='" + newPassword + "' name='newPassword' id='newPassword' />");
			out.println("</p>");
			out.println("<p>");
			out.println("<label for='newPassword2'>Re-Type Your New Password:</label>");
			out.println("<input type='password' value='" + newPassword2 + "' name='newPassword2' id='newPassword2' />");

			if (isNewPasswordError)
				out.println("<span class='error'>Passwords do not match</span>");

			out.println("</p>");
			out.println("</fieldset>");
			out.println("<fieldset class='step'>");
			out.println("<legend>Update Password</legend>");
			out.println("<p class='center'>");
			out.println("<input type='submit' value='Update Password' />");
			out.println("</p>");
			out.println("</fieldset>");
			out.println("</form>");
			out.println("</div>");
			out.println("</body>");
			out.println("</html>");	
		}
		else
		{		
			try{
				// Include the driver class
				Class.forName( className );

				// Establish a connection to the database
				Connection connection =
						DriverManager.getConnection(url, dbusername, dbpassword);


				String updateQuery = "UPDATE Employees SET password = '"+newPassword+"' WHERE username = '"+username+"' AND password = '"+oldPassword+"'";
				Statement statement = connection.createStatement();
				statement.executeUpdate(updateQuery);	


				connection.close();

			}
			catch(SQLException e){		
				e.printStackTrace();
			}
			catch(ClassNotFoundException e){
				e.printStackTrace();
			}

			out.println("<html xmlns='http://www.w3.org/1999/xhtml'>");
			out.println("<head>");
			out.println("<meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />");
			out.println("<title>RCP Update Password</title>");
			out.println("<link rel='stylesheet' type='text/css' href='css/style.css' />");
			out.println("<script type='text/javascript' src='js/rightclick.js'></script>");
			out.println("</head>");
			out.println("<body>");
			out.println("<div id='header'>");
			out.println("<h1>Update Successful</h1>");
			out.println("</div>");
			out.println("<div id='wrapper'>");
			out.println("<div id='steps'>");
			
			out.println("<a href='/rcp-svn/" + home + "'> HOME </a>");
			
			out.println("</div>");
			out.println("</div>");
			out.println("</body>");
			out.println("</html>");	
		}
	}

	private boolean identicalChecker(String word1, String word2) {
		if(word1.trim().length() == 0 || word2.trim().length() == 0){
			return true;
		}
		return !word1.equals(word2);
	}

	private boolean onlyAlphabetChecker(String word) {

		if(word.trim().length() == 0){
			return true;
		}

		// The following only Alphabet Checker code was acquired from
		// http://jgeeks.spot.com/2008/10/best-way-to-check-for-all-alphabetic.html
		if(word.matches("^[a-zA-Z]*")){ 
			return false;
		}else{ 
			return true;
		} 

	}



	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
